/** Copyright 2020 Zhejiang Lab and Zhejiang University. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================
*/


import { ROOT_URL } from '../../config'
import axios from 'axios'
import { parseTime, setIsDialogOpen, setDialogContent, hasDuplicates, convertArray2String } from '../utils'

// initial state
const state = {
    reorg_tasks: [],
    options: {},
    errors: "",
    is_dialog_open: false,
    dialog_content: "",
}

// getters
const getters = {
}

// actions
const actions = {
    getReorgOptions({ commit, state }) {
        axios.get(`${ROOT_URL}/api/task/reorg_task_options`, {
        })
            .then((response) => {
                console.log("reorgOptions", response);
                commit('setReorgOptions', response.data)
            })
            .catch((errors) => {
                console.log("error", errors)
                commit('setReorgOptions', {})
                commit('setErrors', errors)
            })
    },
    createReorgTasks({ dispatch, commit, state }, task_info) {
        console.log('task_info', task_info)
        let new_task_info = Object.assign({}, task_info)
        
        console.log('datasets', state.options.datasets)
        console.log('all_models', state.options.models)

        // Datasets Name to ID
        new_task_info.datasets = new_task_info.datasets.map(
            function(selected_dataset_name) { 
                return state.options.datasets.find( dataset => (dataset.name == selected_dataset_name) ).id
            });
        // Model Name to ID
        new_task_info.teacher_models = new_task_info.teacher_models.map(
            function(selected_model_name) { 
                return state.options.models.find( model => (model.name == selected_model_name) ).id
            });
        new_task_info.student_models = new_task_info.student_models.map(
                function(selected_model_name) { 
                    return state.options.models.find( model => (model.name == selected_model_name) ).id
                });
        // Alg name to ID
        new_task_info.algorithms = state.options.algorithms.find( alg => (alg.id)==new_task_info.algorithms )
         
        if (!new_task_info.tasks.length) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "任务类型不得为空")
        }
        else if (new_task_info.algorithms == null){
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "算法不得为空")
        } 
        else if (hasDuplicates(new_task_info.teacher_models)) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "教师模型重复")
        }
        else if (new_task_info.teacher_models.indexOf(null) != -1) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "选择教师模型或删除该选项")
        }
        else if (new_task_info.teacher_models.length < 1) {
            commit("setIsDialogOpen", true)
            commit("setDialogContent", "请至少选择一个教师模型")
        }
        else {
            console.log('the created task', new_task_info)
            axios.post(`${ROOT_URL}/api/task/reorg_tasks`, {
                task_info: new_task_info
            })
            .then((response) => {
                console.log("create ReorgTasks", response);
                commit("setIsDialogOpen", true)
                commit("setDialogContent", "创建成功")
            })
            .catch((errors) => {
                console.log("error", errors)
                commit('setErrors', errors)
                commit("setIsDialogOpen", true)
                commit("setDialogContent", "创建失败! "+errors)
            })
        }
    },
    getReorgTasks({ commit, state }) {
        axios.get(`${ROOT_URL}/api/task/reorg_tasks`, {
        })
            .then((response) => {
                console.log("ReorgTasks", response.data);
                let tasks = response.data;
                for (let t of tasks) {
                    console.log("task", t)
                    t.created_time = parseTime(t.created_time);
                    t.started_time = parseTime(t.started_time);
                    t.completed_time = parseTime(t.completed_time);
                    t.tasks = t.tasks.reduce(convertArray2String);
                    if (t.datasets) {
                        t.datasets = t.datasets.reduce(convertArray2String);
                    }
                    else {
                        t.datasets = '--'
                    }
                }
                commit('setReorgTasks', tasks)
            })
            .catch((errors) => {
                console.log("error", errors)
                commit('setReorgTasks', [])
                commit('setErrors', errors)
            })
    },
    deleteReorgTasks({ dispatch, commit, state }, task_ids) {
        console.log('tasks', task_ids)
        axios.delete(`${ROOT_URL}/api/task/reorg_tasks`, {
            params: { task_ids: task_ids }
        })
            .then((response) => {
                console.log('delete success')
                commit("setIsDialogOpen", true)
                commit("setDialogContent", "删除成功")
                dispatch('getReorgTasks')
            })
            .catch((errors) => {
                console.log('delete failure')
                commit('setErrors', errors)
                commit("setIsDialogOpen", true)
                commit("setDialogContent", "删除失败")
                dispatch('getReorgTasks')
            })
    },
}

const mutations = {
    setReorgTasks(state, reorg_tasks) {
        state.reorg_tasks = reorg_tasks
    },
    setReorgOptions(state, options) {
        state.options = options
    },
    setErrors(state, errors) {
        state.errors = errors
    },
    setIsDialogOpen, setDialogContent
}

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations
}